package com.xjgz.aio.socket.pro.extension.plugins;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.ConcurrentLinkedQueue;

public class BlackListPlugin<T> extends AbstractPlugin<T> {

    private final ConcurrentLinkedQueue<BlackListRule> ipBlackList = new ConcurrentLinkedQueue<>();

    @Override
    public AsynchronousSocketChannel shouldAccept(AsynchronousSocketChannel channel) {
        InetSocketAddress inetSocketAddress = null;
        try {
            inetSocketAddress = (InetSocketAddress) channel.getRemoteAddress();
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (BlackListRule rule : ipBlackList) {
            if (!rule.access(inetSocketAddress)) {
                return null;
            }
        }
        return channel;
    }

    public void addRule(BlackListRule rule) {
        ipBlackList.add(rule);
    }

    public void removeRule(BlackListRule rule) {
        ipBlackList.remove(rule);
    }

    public interface BlackListRule {

        boolean access(InetSocketAddress address);
    }
}
